//
//  ZHMainRunloopObserver.m
//  ZYT_IOS
//
//  Created by 正合适 on 2018/1/23.
//  Copyright © 2018年 正合适. All rights reserved.
//



#import "ZHMainRunloopObserver.h"
#import <UIKit/UIKit.h>
#import <SVProgressHUD/SVProgressHUD.h>

#define kPerTime 50
static NSString *kLoopThreadName = @"loopThreadName";

@interface ZHMainRunloopObserver ()
{
    // 观察主线程的状态
    CFRunLoopObserverRef observer;
    // 主线程当前的状态
    CFRunLoopActivity currentActivity;
    // 信号量
    dispatch_semaphore_t semaphore;
    // 记录卡顿的次数
    int count;
}

/**卡顿监听的线程*/
@property (nonatomic, strong) NSThread *loopThread;

@end

@implementation ZHMainRunloopObserver
- (instancetype)init {
    self = [super init];
    if (self) {
        [self createSemaphore];
        [self createThread];
        [self createObserver];
    }
    return self;
}

- (void)createThread {
    if (!_loopThread) {
        _loopThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadAction) object:nil];
        [_loopThread setName:kLoopThreadName];
        [_loopThread start];
    }
}

- (void)createObserver {
    if (!observer) {
        observer = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
            currentActivity = activity;
            dispatch_semaphore_signal(semaphore);
        });
        CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopCommonModes);
    }
}

- (void)createSemaphore {
    semaphore = dispatch_semaphore_create(0);
}

- (void)threadAction {
    while (YES) {
        long result = dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, kPerTime*NSEC_PER_MSEC));
        if (result != 0) {
            if (currentActivity == kCFRunLoopBeforeSources || currentActivity == kCFRunLoopAfterWaiting) {
                count+=1;
                continue;
            }
        }
        if (count >= 5) {
            // 处理卡顿
#if DEBUG
            dispatch_sync(dispatch_get_main_queue(), ^{
                [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"主线程卡顿%d毫秒",kPerTime*count]];
            });
#endif
        }
        count = 0;
    }
}
@end
